import axios from "axios";
import { http } from "../utils/http";
import { BASE_URL } from "../utils/http/core";
import { ReturnDTO } from "./type";

const prefix = "/file";

// 上传
export const upload = (
  path: string,
  formData: FormData
): Promise<ReturnDTO> => {
  const newRequest = axios.create({
    baseURL: BASE_URL
  });
  const info = JSON.parse(sessionStorage.getItem("info"));
  if (info) {
    return new Promise((resolve, reject) =>
      newRequest({
        method: "POST",
        url: prefix + "/" + path,
        data: formData,
        headers: {
          "Content-Type":
            "multipart/form-data;boundary=ebf9f03029db4c2799ae16b5428b06bd1",
          header: info.token
        }
      })
        .then((response: any) => {
          resolve(response);
        })
        .catch((error: any) => {
          reject(error);
        })
    );
  }
};

// 通过文件名下载
export const downloadByName = (fileName: string): Promise<ReturnDTO> => {
  return http.request("get", prefix + "/name/" + fileName);
};

// 通过id删除
export const deleteById = (id: number): Promise<ReturnDTO> => {
  return http.request("delete", prefix + "/" + id);
};

// 通过文件id下载
export const downloadById = (id: number): void => {
  axios
    .get(BASE_URL + prefix + "/" + id, {
      responseType: "blob"
    })
    .then(res => {
      console.log(res);
      const blob = res.data;
      const reader = new FileReader();
      reader.readAsDataURL(blob);
      reader.onload = e => {
        const a = document.createElement("a");
        // console.log(res);
        let fileName = res.headers["content-disposition"].split("=");
        fileName = fileName[fileName.length - 1];
        fileName = fileName.replace(/"/g, "");
        a.download = fileName;
        a.href = e.target.result as string;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      };
    });
};
